#include <iostream>
#include <string>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <vector>
#include "util/protocol.hpp" // 复用协议代码
#include <nlohmann/json.hpp>

using json = nlohmann::json;

void send_request(int sock, protocol::MsgType type, const std::string& content) {
    protocol::Message request;
    request.tag = static_cast<int32_t>(type);
    request.value = content;
    request.length = content.size();
    
    std::string data = request.serialize();
    send(sock, data.c_str(), data.size(), 0);
}

void receive_response(int sock) {
    char buffer[8192];
    protocol::MessageParser parser;
    
    int n = recv(sock, buffer, sizeof(buffer) - 1, 0);
    if (n <= 0) {
        std::cout << "服务器已断开或出错" << std::endl;
        return;
    }

    size_t processed = 0;
    auto messages = parser.parse(buffer, n, processed);
    
    if(messages.empty()){
        std::cout << "收到不完整的响应，请重试" << std::endl;
        return;
    }

    for(const auto& msg : messages) {
        std::cout << "\n===== 收到服务器响应 =====\n";
        json resp_json = json::parse(msg.value, nullptr, false);
        if(resp_json.is_discarded()){
            std::cout << "JSON 解析失败: " << msg.value << std::endl;
        } else {
             std::cout << resp_json.dump(4) << std::endl; // 格式化输出
        }
        std::cout << "==========================\n" << std::endl;
    }
}


int main() {
    int sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock < 0) {
        perror("socket");
        return 1;
    }

    struct sockaddr_in serv_addr;
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(8888);
    inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr);

    if (connect(sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) < 0) {
        perror("connect");
        return 1;
    }

    std::cout << "已连接到服务器。\n输入 'kw <词语>' 进行关键字推荐\n输入 'se <句子>' 进行网页搜索\n输入 'exit' 退出。" << std::endl;

    std::string line;
    while (std::cout << "> " && std::getline(std::cin, line) && line != "exit") {
        if (line.rfind("kw ", 0) == 0 && line.size() > 3) {
            send_request(sock, protocol::MsgType::KEYWORD_RECOMMEND_REQ, line.substr(3));
            receive_response(sock);
        } else if (line.rfind("se ", 0) == 0 && line.size() > 3) {
            send_request(sock, protocol::MsgType::PAGE_SEARCH_REQ, line.substr(3));
            receive_response(sock);
        } else {
            std::cout << "无效指令或内容为空。" << std::endl;
        }
    }

    close(sock);
    return 0;
}
